var express = require('express');
var router = express.Router();
let formidable = require("formidable");
let fs = require("fs");
const { resolve } = require('path');
let path = require("path");
let time = require("time-stamp");


router.get("/upload", (req, res) => {
    res.render("pages/upload.html")
})

// form.parse(request,(err,file,fildes)=>{})

router.post("/upload", (req, res) => {
    let form =  new formidable.IncomingForm() 
       //跨磁盘 把原来上传默认的虚拟地址指向到当前项目下
    form.uploadDir ='D:/Offcn/EP3/day10/xiaou' + "/temp";
    form.parse(req, (err, files, fildes) => {
        // console.log(fildes);
        let uploadfiles = fildes.pic1;
        // console.log(uploadfiles);

        //上传图片更名  随机数+时间戳
        let r = parseInt(Math.random() * 10000)
        //时间戳
        let t = time("YYYYMMDD");
        //获取上传图片后缀名
        let extname = path.extname(uploadfiles.originalFilename)
        //console.log(extname);

        //规划上传图片地址
        //D:\Users\Desktop\0511\day9\代码/upload/638120220726.jpg
        let newpath ='D:/Offcn/EP3/day10/xiaou' + "/upload/" + r + t + extname;
        console.log(newpath);

        //获取原来地址
        //c:
        let oldpath = uploadfiles.filepath;
        console.log(oldpath);
        //上传图片
        //方法是不能跨磁盘操作
        fs.rename(oldpath, newpath, (err) => {
            if (err) {
                res.send("上传失败")
            } else {
                res.send("上传成功")
            }
        })
    })
})
module.exports = router;